package com.xcc.core.netty.server;


import java.math.BigInteger;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.xcc.core.netty.manager.ManagerChannel;
import com.xcc.core.netty.model.LengthModel;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 
 * <简述>
 * <详细描述>代理端服务器
 * @author   xcc
 * @version  $Id$
 * @since
 * @see
 */
public class Server3389handler  extends SimpleChannelInboundHandler<ByteBuf> {

    private static final Log LOG = LogFactory.getLog(Server3389handler.class);


    @Override
    public void channelActive(ChannelHandlerContext ctx)
        throws Exception {
        //      int id=Integer.parseInt(ctx.channel().id().asShortText(), 16);
        int   id=  new BigInteger(ctx.channel().id()
            .asShortText(), 16).intValue();
        System.out.println("外部服务:"+id);
        ManagerChannel.getAllClient2().put(id+"", ctx.channel());
        Channel ch=ManagerChannel.getAllClient().get("3389");
        LengthModel msg1 =new  LengthModel();
        byte[] bs=("connect").getBytes();
        msg1.setBs(bs);
        msg1.setLength(bs.length);
        msg1.setId(id);
        ch.writeAndFlush(msg1);

    }

    //发给内部客户端
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg)
        throws Exception {
        //     System.out.println("客户端端id："+ctx.channel().id().asLongText());
        Channel ch= ManagerChannel.getClientChannel("3389");

        if(ch.isActive()) {
            LengthModel mLengthModel=new LengthModel();
            byte[] bs=new byte[msg.readableBytes()];
            msg.readBytes(bs);
            //     int id=Integer.parseInt(ctx.channel().id().asShortText(), 16);
            int   id=  new BigInteger(ctx.channel().id()
                .asShortText(), 16).intValue();
            System.out.println("3389id:"+id);
            while(ManagerChannel.getChannelmapper().get(id+"")==null) {
                System.out.println("等待客户端建立连接");
                System.out.println(id);
                Thread.sleep(3000);
            }
            mLengthModel.setId(Integer.parseInt(ManagerChannel.getChannelmapper().get(id+"")));
            mLengthModel.setLength(bs.length);
            System.out.print("发送数据");
            mLengthModel.setBs(bs);
            for(byte b:bs) {
                System.out.print((0xff&b)+" ");
            }
            System.out.println("发送长度："+bs.length);
            if(ch==null) {
                System.out.println("ch null");
            }
            ch.writeAndFlush(mLengthModel);    
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
        throws Exception {
        super.exceptionCaught(ctx, cause);

    }
}
